package com.renderbus.ep;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class NodeClientHandler extends Thread{
	
	private Socket socket;

	public NodeClientHandler(Socket socket) {
		this.socket = socket;
	}

	private BufferedWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new BufferedWriter(new OutputStreamWriter(socketOut));
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}

	public String echo(String msg) {
		return "echo:" + msg;
	}

	public void run() {
		System.out.println("-----------------Client Node start------------------");
		try {
			System.out.println("Node Client---- "
					+ socket.getInetAddress() + ":" + socket.getPort());
			BufferedReader br = getReader(socket);
			BufferedWriter pw = getWriter(socket);
			String msg = null;
			pw.write("execute\r\n");
			pw.flush();
			while ((msg = br.readLine()) != null) {
				System.out.println("Node Client----accept msg" + msg);
//				pw.write(socket.getLocalAddress().getHostAddress().toString()
//						+ ">" + socket.getRemoteSocketAddress().toString()
//						+ " : " + msg + "\r\n");
//				pw.flush();
//				if (msg.equals("Upgrade: websocket"))
//					break;
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("-----------------run end------------------");
	}

}
